// class的封装：
// 变量，就是封装里面，对象的属性。
// 函数，就就封装里面，对象的方法。
class Drag {
  constructor(selecter) {
    this.node = document.querySelector(selecter)
    this.downx = 0;
    this.downy = 0;
    this.movex = 0;
    this.movey = 0;
    this.init();
  }
  // 初始化方法，负责绑定一个MouseDown事件
  init() {
    this.node.onmousedown = (e) => {
      this.fnDown(e)
    }
  }
  // 鼠标按下时的执行的方法
  fnDown(e) {
    this.downx = e.offsetX;
    this.downy = e.offsetY;
    this.node.style.cursor = 'move';
    this.node.onmousemove = (ev) => {
      this.fnMove(ev)
    }
    this.node.onmouseup = () => {
      this.fnUp()
    }
  }

  fnMove(e) {
    this.movex = e.clientX;
    this.movey = e.clientY;
    let left = this.movex - this.downx;
    let top = this.movey - this.downy;
    this.node.style.left = left + 'px'
    this.node.style.top = top + 'px'
  }

  fnUp() {
    this.node.onmousemove = null;
    this.node.onmouseup = null;
    this.node.style.cursor = 'pointer';
  }
}


(function () {

  let myDrag = {
    node: null,
    downx: 0,
    downy: 0,
    movex: 0,
    movey: 0,
    init(selecter) {
      this.node = document.querySelector(selecter);
      this.node.onmousedown = (e) => {
        this.fnDown(e)
      }
    },
    fnDown(ev) {
      this.downx = ev.offsetX;
      this.downy = ev.offsetY;
      this.node.style.cursor = 'move';
      // document.onmousemove
      this.node.onmousemove = (e) => {
        this.fnMove(e)
      }
      this.node.onmouseup = () => {
        this.fnUp()
      }
    },

    fnMove(e) {
      this.movex = e.clientX;
      this.movey = e.clientY;
      let left = this.movex - this.downx;
      let top = this.movey - this.downy;
      this.node.style.left = left + 'px'
      this.node.style.top = top + 'px'
    },
    fnUp() {
      this.node.onmousemove = null;
      this.node.onmouseup = null;
      this.node.style.cursor = 'pointer';
    }
  }

  window.myDrag = myDrag
})()
